package com.group.voting_system.controller;

import cn.yiban.open.Authorize;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.group.voting_system.entity.User;
import com.group.voting_system.exception.RecordNotExistException;
import com.group.voting_system.service.IUserService;
import com.group.voting_system.utils.RestResult;
import com.group.voting_system.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

/**
 * @Author: xyf
 * @Date: 2019/4/15 20:11
 * 登录的统一权限管理
 */
@Controller
public class AuthController {

    private final static String appID = "60a4966d4e29fbcf";
    private final static String appSecret = "63365bbc4b8fd115836fd377319c94e5";
    private final static String URL = "http://47.100.219.132:8089/user/auth";

    @Autowired
    IUserService userService;

//    控制用户投票的登录
    @GetMapping("/user/login")
    public String userLogin(){
        return "login";
    }

    @GetMapping("/user/yiban")
    public String yibanLogin(){

        Authorize authorize = new Authorize(appID, appSecret);
        String url = authorize.forwardurl(URL, "QUERY", Authorize.DISPLAY_TAG_T.WEB);
        return "redirect:" + url;
    }

    @GetMapping("/user/auth")
    public String auth(@RequestParam("code") String code, HttpSession session){
        Authorize authorize = new Authorize(appID, appSecret);
        String json = authorize.querytoken(code, URL);
        ObjectMapper mapper = new ObjectMapper();
        User user = null;
        try {
            HashMap map = mapper.readValue(json, HashMap.class);
            String token = (String) map.get("access_token");
            cn.yiban.open.common.User yibanUser = new cn.yiban.open.common.User(token);
            //获取易班用户具体信息
            HashMap infoJson = mapper.readValue(yibanUser.me(), HashMap.class);
            HashMap infoMap = (HashMap) infoJson.get("info");
            String userid = (String) infoMap.get("yb_userid");
            String username = (String) infoMap.get("yb_username");
            String schoolname = (String) infoMap.get("yb_schoolname");
            String sex = (String) infoMap.get("yb_sex");

            //在创建用户之前，先对用户进行检索
            User existYibanUser = userService.existYibanUser(userid);
            if (existYibanUser != null){
                session.setAttribute("user", existYibanUser);
                return "success";
            }
            user = new User().setJobNumber(userid)
                    .setUsername(username)
                    .setAcademy(schoolname)
                    .setIsYiban('1')
                    .setRole("user");
            if (sex.equals("M"))
                user.setSex(true);
            else
                user.setSex(false);
            boolean b = userService.save(user);
            if (!b)
                return "fail";
        } catch (IOException e) {
            e.printStackTrace();
        }
        session.setAttribute("user", user);
        return  "success";
    }

    @PostMapping("/user/login")
    @ResponseBody
    public RestResult login(@RequestBody User user, HttpServletRequest request) throws RecordNotExistException {

        User user1 = userService.getUserByJobNumAndPass(user);

        if (user1 != null){
            HttpSession session = request.getSession();
            session.setAttribute("user", user1);
            String url = (String) session.getAttribute("voteUrl");
            if (url == null)
                return ResultUtil.success("登录成功，请重新扫码");
            else{
                session.removeAttribute("voteUrl");
                return ResultUtil.success("登录成功", url);
            }

        }

        return ResultUtil.fail("用户名或密码错误");
    }

    @GetMapping("/user/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:login";
    }

}
